#!/usr/bin/env python
# -*-coding:utf-8-*-
# @Time : 2021/9/16 11:46
# @Author : Li Yan
import os

from flask import current_app

from libs.error_code import FileTypeException, AccessForbidden, UploadTypeError
from utils.file_tool import get_file


def validate(obj: object) -> bool:
    validate_access(obj)
    upload_type(obj)
    validate_file(obj)
    return True


def validate_file(obj: object) -> bool:
    img_types = current_app.config['IMAGE_EXTENSIONS']
    video_types = current_app.config['VIDEO_EXTENSIONS']
    all_types = current_app.config['ALL_TYPES']
    master_file = get_file(obj.form['master_uuid'])
    logo_file = get_file(obj.form['logo_uuid'])
    uploadtype = obj.form['upload_type']
    if uploadtype == 'image':
        validate_image(master_file, img_types)
        if logo_file:
            validate_logo(logo_file, img_types)
    elif uploadtype == 'video':
        validate_video(master_file, video_types)
        if logo_file:
            validate_video(logo_file, img_types)
    elif uploadtype == 'file':
        validate_full(master_file, all_types)
    return True


def upload_type(obj: object) -> bool:
    uploadtype = obj.form['upload_type']
    if uploadtype in current_app.config['UPLOAD_TYPE']:
        return True
    raise UploadTypeError()


def validate_access(obj: object) -> bool:
    access = obj.form['access_key']
    secret = obj.form['secret_key']
    if access == current_app.config['ACCESS_KEY'] and secret == current_app.config['SECRET_KEY']:
        return True
    raise AccessForbidden()


def validate_image(filename: str, types: set) -> bool:
    if validate_type(filename, types):
        return True
    raise FileTypeException(msg='请确认后缀名是否在：{' + '、'.join(types) + '} 中。')


def validate_logo(filename: str, types: set) -> bool:
    if validate_type(filename, types):
        return True
    raise FileTypeException(msg='请确认后logo缀名是否在：{' + '、'.join(types) + '} 中。')


def validate_video(filename: str, types: set) -> bool:
    if validate_type(filename, types):
        return True
    raise FileTypeException(msg='请确认后缀名是否在：{' + '、'.join(types) + '} 中。')


def validate_full(filename: str, types: set) -> bool:
    if validate_type(filename, types):
        return True
    raise FileTypeException(msg='请确认后缀名是否在：{' + '、'.join(types) + '} 中。')


def validate_type(file: str, types: set) -> bool:
    if '.' in file:
        ext = file.rsplit('.', 1)[1]
        if ext in ['uploading', 'removing']:
            os.remove(file)
            raise FileTypeException(msg='文件未上传完毕!请重新上传。')
        if ext not in types:
            os.remove(file)
            return False
        return True
    return False
